package whx.springmvc;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import whx.handler.adapter.HandlerAdapter;
import whx.handler.mapping.HandlerMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map;

public class Servlet extends HttpServlet {
    private String contextConfig;

    static Collection<HandlerMapping> HandlerMaps;
    static Collection<HandlerAdapter> HandlerAdapter;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 路由
        // Map<key,value>  key->uri   value 可能是class(指定了处理方法) ，也可能是 method
        // url的指定
        // 映射器
        Object result = null;
        Object myHandler= getHandlerMapping(req);
        //适配器模式 判断什么类型的处理器
        HandlerAdapter handlerAdapter = getHandlerAdapter(myHandler);
        try{
            result =  handlerAdapter.handler(req,resp,myHandler);
        }catch (Exception e){
            e.printStackTrace();
        }
        PrintWriter p = resp.getWriter();
        p.println(result);

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("主servlet启动的初始化方法init(),主要用于获取Collection集合【映射器】【适配器】。。。。。。。。。。");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config.getInitParameter("contextConfig"));
        Map<String,HandlerMapping> handlerMap = context.getBeansOfType(HandlerMapping.class);
        HandlerMaps = handlerMap.values();
        Map<String,HandlerAdapter> handlerAdapter = context.getBeansOfType(HandlerAdapter.class);
        HandlerAdapter = handlerAdapter.values();
    }

    private Object getHandlerMapping(HttpServletRequest req){
        if(HandlerMaps != null){
            for(HandlerMapping h:HandlerMaps){
                Object  handler = h.getHandler(req.getRequestURI());
                if(handler!=null){
                    return handler;
                }
            }

        }
        return null;
    }

    private HandlerAdapter getHandlerAdapter(Object handler){
        if(HandlerAdapter != null){
            for(HandlerAdapter a:HandlerAdapter){
                Boolean flag = a.support(handler);
                if(flag){
                    return a;
                }
            }
        }
        return null;
    }
}
